package com.heer.gymnasium.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.gymnasium.AppHelper;
import com.heer.gymnasium.R;
import com.heer.gymnasium.activity.MainActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.dialog.QRAccessDialog;
import com.heer.gymnasium.dialog.SiteLevelDialog;
import com.heer.gymnasium.event.BaseEvent;
import com.heer.gymnasium.util.LoadImageUtil;
import com.heer.gymnasium.util.ShareUtils;
import com.heer.gymnasium.widget.MyListView;
import com.heer.model.OrderBean;
import com.heer.model.WxPayBean;
import com.heer.gymnasium.util.PayUtils;
import com.mob.tools.utils.Data;

import org.greenrobot.eventbus.EventBus;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.event.EventConstant.CANCEL_ORDER;

/**
 * Created by heer on 17/4/9.
 */

public class OrderAllAdapter extends ListAdapter<OrderBean> {
    private int type;

    public OrderAllAdapter(Activity activity, int type) {
        super(activity);
        this.type = type;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view != null) {
            holder = (ViewHolder) view.getTag();
        } else {
            view = mInflater.inflate(R.layout.item_order_list, parent, false);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }

        switch (type) {
            case Type.ORDER_ALL:
            case Type.ORDER_UNPAID:
                holder.tvTitle.setGravity(Gravity.CENTER);
                holder.btnShare.setVisibility(View.GONE);
                holder.layoutAddress.setVisibility(View.GONE);
                break;
            case Type.ORDER_USABLE:
                holder.tvTitle.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                holder.btnShare.setVisibility(View.VISIBLE);
                holder.layoutAddress.setVisibility(View.VISIBLE);
                break;
        }
        initOrderView(holder, getItem(position));
        return view;
    }

    /**
     * @param holder
     * @param data
     */
    private void initOrderView(final ViewHolder holder, final OrderBean data) {

        switch (data.getTicket().getCat_id()) {
            case Type.SITE_TICKET_TYPE_1://1:门票
            case Type.SITE_TICKET_TYPE_2://2:次卡
            case Type.SITE_TICKET_TYPE_3://3:期卡
                holder.layoutSite.setVisibility(View.GONE);
                holder.layoutCard.setVisibility(View.VISIBLE);
                holder.tvTitle.setText(data.getStadium().getStadiumname() +"("+ data.getTicket().getTicket_name()+")");
                holder.tvSite.setText(data.getStadium().getStadiumname());
                holder.btnShare.setVisibility(View.GONE);
                Glide.with(mActivity)
                        .load(LoadImageUtil.getLoadImageUrl(data.getTicket().getImage()))
                        .placeholder(R.mipmap.ic_order_card)
                        .into(holder.imageCard);
                break;
            case Type.SITE_TICKET_TYPE_4://4:包场
                holder.layoutSite.setVisibility(View.VISIBLE);
                holder.layoutCard.setVisibility(View.GONE);
                holder.btnShare.setVisibility(View.GONE);
                holder.tvTitle.setText(data.getStadium().getStadiumname());
                holder.btn1.setVisibility(View.VISIBLE);
                final OrderSiteTypeAdapter mAdapter = new OrderSiteTypeAdapter(this.mActivity, data.getTicket().getImage());
                holder.lvSite.setAdapter(mAdapter);
                mAdapter.setItems(data.getBooking());
                mAdapter.setCount(1);
                holder.imageArrow.setImageResource(R.mipmap.arrow_down);
                if (data.getBooking().size() > 1)
                    holder.imageArrow.setVisibility(View.VISIBLE);
                else
                    holder.imageArrow.setVisibility(View.GONE);
                holder.layoutSite.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mAdapter.getCount() == 1) {
                            mAdapter.setCount(mAdapter.getItemList().size());
                            holder.imageArrow.setImageResource(R.mipmap.arrow_top);
                        } else {
                            mAdapter.setCount(1);
                            holder.imageArrow.setImageResource(R.mipmap.arrow_down);
                        }
                    }
                });
                break;
        }


        if (TextUtils.equals(data.getStatus(), "0")) {
            holder.tvStatus1.setText("无效");
            holder.tvStatus1.setTextColor(mActivity.getResources().getColor(R.color.colorTextNormal));
            holder.tvStatus1.setVisibility(View.VISIBLE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.GONE);
        } else if (TextUtils.equals(data.getStatus(), "2") || TextUtils.equals(data.getStatus(), "3")) {
            holder.tvStatus1.setText("已取消");
            holder.tvStatus1.setTextColor(mActivity.getResources().getColor(R.color.colorTextNormal));
            holder.tvStatus1.setVisibility(View.VISIBLE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.GONE);
        } else if (TextUtils.equals(data.getStatus(), "1") && Integer.valueOf(data.getStar()) > 0) {
            holder.tvStatus1.setText("已评价");
            holder.tvStatus1.setTextColor(mActivity.getResources().getColor(R.color.colorTextNormal));
            holder.tvStatus1.setVisibility(View.VISIBLE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.GONE);
        } else if (TextUtils.equals(data.getStatus(), "1")
                && Integer.valueOf(data.getStar()) == 0
                && Long.valueOf(data.getFinish_time()) > 0) {
            holder.tvStatus1.setVisibility(View.GONE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.VISIBLE);
            holder.btn2.setText("评价");
            holder.btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new SiteLevelDialog(mActivity, data.getOrder_sn()).show();
                }
            });
        } else if (TextUtils.equals(data.getStatus(), "1")
                && TextUtils.equals(data.getPay_status(), "2")) {
            holder.tvStatus1.setText("请支付补费订单");
            holder.tvStatus1.setTextColor(mActivity.getResources().getColor(R.color.colorTextNormal));
            holder.tvStatus1.setVisibility(View.VISIBLE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.GONE);
            holder.tvTitle.setText("补缴费用");
        } else if (TextUtils.equals(data.getStatus(), "1")
                && TextUtils.equals(data.getPay_status(), "0")
                && data.getParent_id() > 0) {
            holder.tvTitle.setText("补缴费用");
            holder.tvStatus1.setVisibility(View.GONE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.VISIBLE);
            holder.btn2.setText("继续支付");
            holder.btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mActivity, "继续支付", Toast.LENGTH_SHORT).show();
                    if (TextUtils.equals(data.getPay_type(), "ali")) {
                        new PayUtils(mActivity).pay(holder.btn1, data.getPay_money(), data.getOrder_sn());
                    } else if (TextUtils.equals(data.getPay_type(), "wx")) {

                        AppHelper.context().apiService().getWxData(data.getOrder_sn()).enqueue(new BaseCallback<ApiResponse<WxPayBean>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<WxPayBean>> call, Response<ApiResponse<WxPayBean>> response) {
                                super.onResponse(call, response);
                                if (response.isSuccessful() && response.body().isSccessful()) {
                                    WxPayBean data = response.body().getData();
                                    Gson gson = new Gson();
                                    String json = gson.toJson(data);
                                    new PayUtils(mActivity).payWx(json);
                                } else {
                                    Log.e("PAY_GET", "返回错误" + response.message());
                                }
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<WxPayBean>> call, Throwable t) {
                                super.onFailure(call, t);
                            }
                        });

                    }
                }
            });
        } else if (TextUtils.equals(data.getStatus(), "1")
                && TextUtils.equals(data.getPay_status(), "1")
                && data.getParent_id() > 0) {
            holder.tvTitle.setText("补缴费用");
            holder.tvStatus1.setText("已支付");
            holder.tvStatus1.setTextColor(mActivity.getResources().getColor(R.color.colorTextNormal));
            holder.tvStatus1.setVisibility(View.VISIBLE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.GONE);
        } else if (TextUtils.equals(data.getStatus(), "1")
                && TextUtils.equals(data.getStar(), "0")
                && TextUtils.equals(data.getFinish_time(), "0")
                && TextUtils.equals(data.getUsed(), "2")) {
            holder.tvStatus1.setText("已过期");
            holder.tvStatus1.setTextColor(mActivity.getResources().getColor(R.color.colorRed));
            holder.tvStatus1.setVisibility(View.VISIBLE);
            holder.btn1.setVisibility(View.GONE);
            holder.btn2.setVisibility(View.GONE);
        } else if (TextUtils.equals(data.getStatus(), "1")
                && TextUtils.equals(data.getPay_status(), "0")) {
            holder.tvStatus1.setVisibility(View.GONE);
            holder.btn1.setVisibility(View.VISIBLE);
            holder.btn2.setVisibility(View.VISIBLE);
            holder.btn1.setText("取消");
            holder.btn2.setText("继续支付");
            holder.btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setMessage("确认取消吗？");
                    builder.setTitle("提示");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            AppHelper.context()
                                    .apiService()
                                    .orderCancel(data.getOrder_sn())
                                    .enqueue(new BaseCallback<ApiResponse>() {
                                                 @Override
                                                 public void onResponse
                                                         (Call<ApiResponse> call, Response<ApiResponse> response) {
                                                     super.onResponse(call, response);
                                                     if (response.isSuccessful() && response.body().isSccessful()) {
                                                         Toast.makeText(mActivity, "取消成功", Toast.LENGTH_SHORT).show();
                                                         OrderAllAdapter.this.itemList.remove(data);
                                                         notifyDataSetChanged();
                                                     } else {
                                                         Toast.makeText(mActivity, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                                     }
                                                 }

                                                 @Override
                                                 public void onFailure(Call<ApiResponse> call, Throwable t) {
                                                     super.onFailure(call, t);
                                                 }
                                             }

                                    );
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
            });
            holder.btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mActivity, "继续支付", Toast.LENGTH_SHORT).show();
                    if (TextUtils.equals(data.getPay_type(), "ali")) {
                        new PayUtils(mActivity).pay(holder.btn1, data.getPay_money(), data.getOrder_sn());
                    } else if (TextUtils.equals(data.getPay_type(), "wx")) {

                        AppHelper.context().apiService().getWxData(data.getOrder_sn()).enqueue(new BaseCallback<ApiResponse<WxPayBean>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<WxPayBean>> call, Response<ApiResponse<WxPayBean>> response) {
                                super.onResponse(call, response);
                                if (response.isSuccessful() && response.body().isSccessful()) {
                                    WxPayBean data = response.body().getData();
                                    Gson gson = new Gson();
                                    String json = gson.toJson(data);
                                    new PayUtils(mActivity).payWx(json);
                                } else {
                                    Log.e("PAY_GET", "返回错误" + response.message());
                                }
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<WxPayBean>> call, Throwable t) {
                                super.onFailure(call, t);
                            }
                        });

                    }
                }
            });
        } else if (TextUtils.equals(data.getStatus(), "1")
                && TextUtils.equals(data.getPay_status(), "1")
                && data.getParent_id() == 0
                && Integer.valueOf(data.getUsed()) < 2) {
            holder.tvStatus1.setVisibility(View.GONE);
            if (TextUtils.equals(data.getTicket().getCat_id(), Type.SITE_TICKET_TYPE_4)) {
                holder.btnShare.setVisibility(View.VISIBLE);
            } else {
                holder.btnShare.setVisibility(View.GONE);
            }
            holder.btnShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShareUtils.showShare(mActivity, ShareUtils.getShareUrl(data.getOrder_sn()),"入场电子门票");
                }
            });

            holder.btn1.setVisibility(View.VISIBLE);
            holder.btn2.setVisibility(View.VISIBLE);
            holder.btn1.setText("取消");
            holder.btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setMessage("确认取消吗？");
                    builder.setTitle("提示");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            AppHelper.context().apiService().orderCancel(data.getOrder_sn()).enqueue(new BaseCallback<ApiResponse>() {
                                @Override
                                public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                                    super.onResponse(call, response);
                                    if (response.isSuccessful() && response.body().isSccessful()) {
                                        Toast.makeText(mActivity, "取消成功", Toast.LENGTH_SHORT).show();
                                        OrderAllAdapter.this.itemList.remove(data);
                                        notifyDataSetChanged();
                                        BaseEvent event = new BaseEvent(CANCEL_ORDER,"");
                                        EventBus.getDefault().post(event);
                                    } else {
                                        Toast.makeText(mActivity, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                }

                                @Override
                                public void onFailure(Call<ApiResponse> call, Throwable t) {
                                    super.onFailure(call, t);
                                }
                            });
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
            });

            if (TextUtils.equals(data.getAccess_status(), "0")) {
                holder.btn2.setText("入场券");
                holder.btn2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Toast.makeText(mActivity, "入场券", Toast.LENGTH_SHORT).show();
                        //new QRAccessDialog(mActivity, data.getOrder_sn()).show();
                        ((MainActivity) mActivity).switchPages(2);
                        ((MainActivity) mActivity).mFragmentContainerHelper.handlePageSelected(2);
                    }
                });
            } else {
                holder.btn2.setText("出场券");
                holder.btn2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(mActivity, "出场券", Toast.LENGTH_SHORT).show();
                        new QRAccessDialog(mActivity, data.getOrder_sn()).show();
                    }
                });
            }
        }

        if (TextUtils.equals(data.getUse_num(), "0"))

        {
            holder.tvStatus.setText("未使用");
        } else

        {
            holder.tvStatus.setText("已使用"+data.getUse_num()+"次");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        long  l = Long.valueOf(data.getStime());


        holder.tvStime.setText("有效期："+sdf.format(new Date(l*1000L)));

    }

    static class ViewHolder {
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.btn_share)
        TextView btnShare;
        @BindView(R.id.image_card)
        ImageView imageCard;
        @BindView(R.id.tv_site)
        TextView tvSite;
        @BindView(R.id.tv_status)
        TextView tvStatus;
        @BindView(R.id.tv_status1)
        TextView tvStatus1;
        @BindView(R.id.layout_address)
        LinearLayout layoutAddress;
        @BindView(R.id.layout_card)
        LinearLayout layoutCard;
        @BindView(R.id.lv_site)
        MyListView lvSite;
        @BindView(R.id.image_arrow)
        ImageView imageArrow;
        @BindView(R.id.layout_site)
        RelativeLayout layoutSite;
        @BindView(R.id.btn_1)
        TextView btn1;
        @BindView(R.id.btn_2)
        TextView btn2;
        @BindView(R.id.layout_item)
        LinearLayout layoutItem;
        @BindView(R.id.tv_orderitem_stime)
        TextView tvStime;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
